<template>
  <div class="comment-management">
    <!-- 搜索和操作区域 -->
    <div class="operation-area">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchQuery"
            placeholder="搜索评论内容/用户"
            clearable
            @clear="handleSearch"
          >
            <template #suffix>
              <el-icon class="el-input__icon" @click="handleSearch">
                <Search />
              </el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterStatus" placeholder="评论状态" @change="handleSearch">
            <el-option label="全部" value="" />
            <el-option label="待审核" value="pending" />
            <el-option label="已发布" value="approved" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-switch
            v-model="isTreeMode"
            active-text="树状结构"
            inactive-text="列表结构"
            @change="handleModeChange"
          />
        </el-col>
      </el-row>
    </div>

    <!-- 添加包装器div -->
    <div class="table-wrapper">
      <!-- 树状结构表格 -->
      <el-table
        v-if="isTreeMode"
        :data="treeComments"
        style="width: 100%"
        v-loading="loading"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        max-height="calc(100vh - 220px)"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="content" label="评论内容" min-width="300">
          <template #default="scope">
            <div class="comment-content">
              <div class="comment-text">{{ scope.row.content }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="评论用户" width="120" />
        <el-table-column prop="createTime" label="评论时间" width="180" >
          <template #default="scope">
            {{formatDate(scope.row.createTime)}}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === 'pending'"
              type="success" 
              link 
              @click="handleApprove(scope.row)"
            >
              通过
            </el-button>
            <el-button 
              v-if="scope.row.status === 'pending'"
              type="danger" 
              link 
              @click="handleReject(scope.row)"
            >
              拒绝
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              删除
            </el-button>
            <el-button type="primary" link @click="viewPost(scope.row)">
              查看帖子
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 列表结构表格 -->
      <el-table
        v-else
        :data="filteredComments"
        style="width: 100%"
        v-loading="loading"
        max-height="calc(100vh - 240px)"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="content" label="评论内容" min-width="300">
          <template #default="scope">
            <div class="comment-content">
              <div class="post-title">
                <span v-if="scope.row.lastId">
                  回复评论ID: {{ scope.row.lastId }}
                </span>
                <span v-else>主评论</span>
              </div>
              <div class="comment-text">{{ scope.row.content }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="评论用户" width="120" />
        <el-table-column prop="createTime" label="评论时间" width="180" >
          <template #default="scope">
            {{formatDate(scope.row.createTime)}}
          </template>
          </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === 'pending'"
              type="success" 
              link 
              @click="handleApprove(scope.row)"
            >
              通过
            </el-button>
            <el-button 
              v-if="scope.row.status === 'pending'"
              type="danger" 
              link 
              @click="handleReject(scope.row)"
            >
              拒绝
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              删除
            </el-button>
            <el-button type="primary" link @click="viewPost(scope.row)">
              查看帖子
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[50,100,200,500]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredTotal"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import {deleteCommentAPI} from "@/apis/notes";

// 数据
const searchQuery = ref('')
const filterStatus = ref('')
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(50)
const total = ref(0)
const commentList = ref([])

// 树状模式开关
const isTreeMode = ref(false)
//const treeComments = ref([])

// 添加 computed 属性用于筛选
const filteredComments = computed(() => {
  return commentList.value.filter(comment => {
    // 状态筛选
    const statusMatch = !filterStatus.value || comment.status === filterStatus.value
    
    // 搜索筛选（评论内容或用户名）
    const searchLower = searchQuery.value.toLowerCase()
    const contentMatch = comment.content.toLowerCase().includes(searchLower)
    const userMatch = comment.username.toLowerCase().includes(searchLower)
    
    return statusMatch && (contentMatch || userMatch)
  })
})

// 更新树状结构的计算属性
const treeComments = computed(() => {
  return convertToTree(filteredComments.value)
})

// 将列表数据转换为树状结构
function convertToTree(list) {
  const map = {}
  const result = []

  list.forEach(item => {
    map[item.id] = {
      ...item,
      children: []
    }
  })
  // 构建树状结构
  list.forEach(item => {
    const node = map[item.id]
    if (item.lastId) {
      //回复评论
      const parent = map[item.lastId]
      if (parent) {
        parent.children.push(node)
      } else {
        //如果找不到父评论，就放在顶层
        result.push(node)
      }
    } else {
      //主评论
      result.push(node)
    }
  })

  return result
}

//模式切换
function handleModeChange(val) {
  if (val) {
    //切换到树状模式
    treeComments.value = convertToTree(commentList.value)
  }
}

// 更新获取数据的方法
async function fetchComments() {
  loading.value = true
  try {
    const response = await axios.get('http://localhost:9090/discuss/selectPage', {
      params: {
        pageSize: pageSize.value,
        pageNum: currentPage.value,
      }
    })
    
    if (response.data.code === '200') {
      commentList.value = response.data.data.list.map(item => ({
        nid:item.nid,
        id: item.discussId,
        content: item.content,
        username: item.publisherName,
        createTime: item.createTime,
        lastId: item.lastId,
        status: 'approved'
      }))
      total.value = response.data.data.total
      
      // 如果当前是树状模式，更新树状数据
      if (isTreeMode.value) {
        treeComments.value = convertToTree(commentList.value)
      }
    }
  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 状态相关方法
function getStatusType(status) {
  const types = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return types[status] || 'info'
}

function getStatusText(status) {
  const texts = {
    pending: '待审核',
    approved: '已发布',
    rejected: '已拒绝'
  }
  return texts[status] || '未知'
}

// 更新搜索方法
function handleSearch() {
  currentPage.value = 1
  fetchComments()
}

function handleApprove(row) {
  ElMessageBox.confirm(
    '确定通过这条评论吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
    }
  ).then(() => {
    row.status = 'approved'
    ElMessage.success('评论已通过')
  })
}

function handleReject(row) {
  ElMessageBox.confirm(
    '确定拒绝这条评论吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    row.status = 'rejected'
    ElMessage.success('评论已拒绝')
  })
}

function handleDelete(row) {
  ElMessageBox.confirm(
    '确定要删除该评论吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    await deleteCommentAPI(row.id).then(res=>{
      if(res.code==='200'){
        ElMessage.success('删除成功')
        fetchComments()
      }else {
        ElMessage.error(res.msg)
      }
    })

  })
}

function viewPost(row) {
  window.open(`http://localhost:5173/post/${row.nid}`, '_blank')
}

// 更新分页方法
function handleSizeChange(val) {
  pageSize.value = val
  fetchComments()
}

function handleCurrentChange(val) {
  currentPage.value = val
  fetchComments()
}

function formatDate(date) {
  const target=new Date(date)
  return `${target.toLocaleDateString()}`+` ${target.toLocaleTimeString()}`
}

// 更新总数计算
const filteredTotal = computed(() => {
  return filteredComments.value.length
})

onMounted(() => {
  fetchComments()
})
</script>

<style scoped>
.comment-management {
  padding: 20px;
  height: 100%;
}

.operation-area {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.comment-content {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.post-title {
  color: #666;
  font-size: 13px;
  margin-bottom: 5px;
}

.comment-text {
  color: #333;
  padding-left: 10px;
  border-left: 2px solid #eee;
}

.el-select {
  width: 100%;
}

.operation-area .el-switch {
  margin-top: 5px;
}

/* 树状结构的缩进样式 */
:deep(.el-table__row--level-1) .comment-text {
  padding-left: 20px;
}

:deep(.el-table__row--level-2) .comment-text {
  padding-left: 40px;
}

.table-wrapper {
  margin: 20px 0;
}

/* 自定义滚动条样式 */
:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: #dcdfe6;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: #f5f7fa;
}
</style>
